import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const SYSID = process.env.SYSID

const CancelToken = axios.CancelToken
const source = CancelToken.source()

const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 30000, // request timeout
  cancelToken: source.token
})

service.defaults.timeout = 30000

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    // config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['Cache-Control'] = 'no-cache'
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  // response => response,
  /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
  response => {
    // console.log(response.data)
    /**
         * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
         * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
         */

    const res = response.data
    if (response.status === 401 || (res.Meta && res.Meta.Code === 40101)) {
      MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
      return Promise.reject('error')
    }

    if (res.Meta && res.Meta.Code === 301) {
      MessageBox.confirm('您的登录状态已超时，请重新登录！', '登录超时', {
        confirmButtonText: '重新登录',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
      return response.data
    }

    if (res.Meta && res.Meta.Code === 40301) {
      Message({
        message: '当前用户无相关操作权限！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }

    if (response.status !== 200 || (res.Meta && (res.Meta.Code !== 0 && res.Meta.Code !== '0'))) {
      if (res.Meta.Code == 201) return Promise.reject(res.Meta.Code) // 201代表数据重复 增加用户判断
      Message({ message: res.Meta.Message, type: 'error', duration: 5 * 1000 })
    } else {
      // console.log(response.data)
      return response.data
    }

    // return response.data
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: '请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export function requestHttp(url, method, reqdata) {
  return new Promise((resolve, reject) => {
    var reqparams = {
      url: url,
      method: method,
      timeout: 30000
    }
    // reqdata['sysId'] = store.getters.sysid
    reqdata['sysId'] = SYSID
    if (method === 'post') {
      reqparams['data'] = reqdata
    } else {
      reqparams['params'] = reqdata
    }
    service.request(reqparams).then(res => {
      var data = res
      var nerrcode = -1
      var strerrmsg = '解析格式错误'

      if (data.Meta !== undefined ||
                data.RS1 !== undefined) {
        var rethead = data.Meta
        if (data.RS1 !== undefined) {
          rethead = data.RS1[0]
        }
        if (rethead !== undefined) {
          if (rethead.Code !== undefined) {
            nerrcode = rethead.Code
            strerrmsg = rethead.Message
          } else {
            nerrcode = rethead.CODE
            strerrmsg = rethead.MSG
          }
        }
        if (nerrcode === '0' || nerrcode === 0) {
          var retdata = data.Data
          if (retdata !== undefined) {
            return resolve(retdata)
          }
        }
      }

      reject(strerrmsg)
    }).catch(error => {
      reject(error)
    })
  })
}

export function downloadRequest(url, method = 'post', reqdata) {
  const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 20000, // request timeout
    cancelToken: source.token
  })

  service.defaults.timeout = 30000

  // request interceptor
  service.interceptors.request.use(config => {
    // Do something before request is sent
    if (store.getters.token) {
      // config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['Cache-Control'] = 'no-cache',
      config.headers['Content-Type'] = 'application/json; application/octet-stream'
      config.responseType = 'blob'
    }
    return config
  }, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  })

  // respone interceptor
  service.interceptors.response.use(
    // response => response,
    /**
         * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
         * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
         */
    response => {
      // console.log(response.data)
      /**
             * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
             * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
             */

      const res = response.data
      if (response.status === 401 || (res.Meta && res.Meta.Code === 40101)) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        return Promise.reject('error')
      }

      if (res.Meta && res.Meta.Code === 301) {
        MessageBox.confirm('您的登录状态已超时，请重新登录！', '登录超时', {
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        return response.data
      }

      if (res.Meta && res.Meta.Code === 40301) {
        Message({
          message: '当前用户无相关操作权限！',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      }

      if (response.status !== 200 || (res.Meta && (res.Meta.Code !== 0 && res.Meta.Code !== '0'))) {
        if (res.Meta.Code == 201) return Promise.reject(res.Meta.Code) // 201代表数据重复 增加用户判断
        Message({ message: res.Meta.Message, type: 'error', duration: 5 * 1000 })
      } else {
        // console.log(response.data)
        return response.data
      }

      // return response.data
    },
    error => {
      console.log('err' + error) // for debug
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    })
  return new Promise((resolve, reject) => {
    var reqparams = {
      url: url,
      method: method,
      timeout: 30000
    }
    // reqdata['sysId'] = store.getters.sysid
    reqdata['sysId'] = SYSID
    if (method === 'post') {
      reqparams['data'] = reqdata
    } else {
      reqparams['params'] = reqdata
    }
    service.request(reqparams).then(res => {
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

export function requestGet(url, reqdata) {
  return requestHttp(url, 'get', reqdata)
}

export function requestPost(url, reqdata) {
  return requestHttp(url, 'post', reqdata)
}

export function doRequestHttp(url, method, reqdata, options) {
  return new Promise((resolve, reject) => {
    var reqparams = {
      url: url,
      method: method,
      timeout: options && options.timeout ? options.timeout : 30000
    }
    reqdata['sysId'] = SYSID
    if (method === 'post' || method === 'put') {
      reqparams['data'] = reqdata
    } else {
      reqparams['params'] = reqdata
    }
    service.request(reqparams).then(res => {
      var data = res
      var nerrcode = -1
      var strerrmsg = '解析格式错误'

      if (data.Meta !== undefined) {
        return resolve(res)
      }

      // return resolve(res)

      reject(strerrmsg)
    }).catch(error => {
      if (axios.isCancel(error)) { // 用户取消请求
        console.log(err.message) // 获取source.cancel 中的内容
      }
      reject(error)
    })
  })
}

export function doRequestGet(url, reqdata) {
  return doRequestHttp(url, 'get', reqdata)
}

export function doRequestPost(url, reqdata, options) {
  return doRequestHttp(url, 'post', reqdata, options)
}

export function doRequestPut(url, reqdata) {
  return doRequestHttp(url, 'put', reqdata)
}

export function doRequestDel(url, reqdata) {
  return doRequestHttp(url, 'delete', reqdata)
}

export function doRequestPage(url, reqdata, type) {
  if (type === 'post') {
    return doRequestPost(url, reqdata)
  } else {
    reqdata.PageSize = reqdata.PageInfo.PageSize
    reqdata.PageNum = reqdata.PageInfo.PageNum
    reqdata.Total = reqdata.PageInfo.Total
    return doRequestGet(url, reqdata)
  }
}

// 91测试服务器
// export const baseUrl = 'http://192.168.9.91:8088/information/'

// 锐
// export const baseUrl = 'http://192.168.10.148:8088/information/'

// 超
// export const baseUrl = 'http://192.168.10.236:8088/information/'

// 银河测试服务器
// export const baseUrl = 'http://10.8.8.159:8088/information/'
// 阿里云服务器地址
// export const baseUrl = 'http://nmp.information.mdengta.com/information/'
// 银河测试服务器
// export const baseUrl = 'http://10.8.99.119:3001/information/'
// 沈阳
// export const baseUrl = 'http://9.1.195.89:8088/information/'
// zhanghui
// export const baseUrl = 'http://9.1.195.77:8088/information/'
// 银河生产服务器 - 116
// export const baseUrl = 'http://10.8.99.116:3001/information/'
// 银河生产服务器 - 147
// export const baseUrl = 'http://10.8.8.147:3001/information/'

// 国元证券生产服务器
export const baseUrl = 'http://122.112.132.105:3001/information/'

// 主要是判断上传
export const isPord = true

export default service
